package com.hna.eking.framework.exception;

import com.hna.eking.service.framework.common.ErrorCode;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BadRequestParamException extends RuntimeException {
    private List<FieldError> fieldErrors;

    public BadRequestParamException(String message) {
        super(message);
    }

    public BadRequestParamException(List<FieldError> fieldErrors) {
        super(ErrorCode.ERROR_GLOBAL_PARAM_ERROR.getMessage());
        this.fieldErrors = fieldErrors;
    }

    public BadRequestParamException(FieldError fieldError) {
        this(Arrays.asList(fieldError));
    }


    public List<FieldError> getFieldErrors() {
        return fieldErrors;
    }

    public void setFieldErrors(List<FieldError> fieldErrors) {
        this.fieldErrors = fieldErrors;
    }


    public List<ErrorInfo> getErrorInfoList() {
        List<ErrorInfo> errorInfoList = new ArrayList<>();
        if (fieldErrors == null || fieldErrors.size() == 0) {
            return errorInfoList;
        }

        for (FieldError error : fieldErrors) {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.setKey(error.getField());
            errorInfo.setMessage(error.getDefaultMessage());
            errorInfoList.add(errorInfo);

        }
        return errorInfoList;
    }


    public static class ErrorInfo {
        String key;//错误字段
        String message;//错误

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}
